package main

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"net/smtp"
	"time"

	"github.com/jordan-wright/email"
	"github.com/zeromicro/go-zero/core/logx"
)

func SendMail(server string, host, from string, pwd string, to []string, subject, msg string) error {
	// host: smtp.exmail.qq.com:465
	// from: xiaobai@innovsharing.com
	// user: xiaobai@innovsharing.com
	// password: TQjGpKvm7azBYD4q

	e := email.NewEmail()
	// 设置发送方的邮箱
	e.From = from
	// 设置接收方的邮箱
	e.To = to
	// 设置主题
	e.Subject = subject
	// 设置文件发送的内容
	e.HTML = []byte(msg)
	// 设置服务器相关的配置
	go func() {
		// 这个需要使用  tls 的配置, 否则发送失败
		err := e.SendWithTLS(server, smtp.PlainAuth("", from, pwd, host), &tls.Config{ServerName: host})
		if err != nil {
			logx.Errorf("send email to %s err : %s", to[0], err.Error())
		}
	}()

	return nil
}

func SendEmailAccount(server string, host, from string, pwd string, userEmail, userPwd string, appMap map[string]string) {
	appAdds := ""
	for name, url := range appMap {
		appAdds += "<div> " + url + " ( " + name + " ) </div>"
	}
	message := "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <title>邮箱开通通知</title>\n</head>\n<body>\n    <div style=\"width: 100%; height: auto; margin: 20px 20px 0\">\n        <h4>欢迎使用，您的账号已开通，账号信息如下：</h4>\n        <div>登录地址：</div>\n    " + appAdds + "     \n        <div>账号: " + userEmail + " </div>\n        <div>密码：" + userPwd + "（默认密码，进入系统可自行重置）</div>\n        <div>您可用此账号登录以上各个系统~</div>\n        <div style=\"font-size: 12px;color: #333;\">\n            <br>\n            <br>\n            <div>——————————————————————</div>\n            <div>本邮件由系统自动发出，请勿直接回复。谢谢！</div>\n        </div>\n    </div>\n</body>\n</html>"

	var to = []string{userEmail}
	err := SendMail(host, server, from, pwd, to, "账户开通提醒", message)

	if err != nil {
		logx.Error(fmt.Sprintf("邮件(%s)发送错误: %s", userEmail, err.Error()))
	}
}

type emails struct {
	Host     string `json:"host,omitempty" from:"host" gorm:"host" bson:"host"`
	Server   string `json:"server,omitempty" from:"server" gorm:"server" bson:"server"`
	From     string `json:"from,omitempty" from:"from" gorm:"from" bson:"from"`
	User     string `json:"user,omitempty" from:"user" gorm:"user" bson:"user"`
	Password string `json:"password,omitempty" from:"password" gorm:"password" bson:"password"`
}

func main() {
	jsonStr := `{
		"Host": "smtp.exmail.qq.com:465",
	  "Server": "smtp.exmail.qq.com",
	  "From": "xiaobai@innovsharing.com",
	  "User": "xiaobai@innovsharing.com",
	  "Password": "TQjGpKvm7azBYD4q"
	}`
	var mail emails
	err := json.Unmarshal([]byte(jsonStr), &mail)
	if err != nil {
		panic(err.Error())
	}

	var apps = make(map[string]string)
	apps["demo"] = "http://baidu.com"
	SendEmailAccount(mail.Server, mail.Host, mail.From, mail.Password, "anziguoer@163.com", "xxkj2022", apps)
	time.Sleep(10 * time.Second)
}
